package cn.master.volley.commons;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;

import org.apache.http.protocol.HTTP;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


/**
 * 自定义请求头的Request
 */
public class CustomHeaderRequest extends StringRequest {
	
	private static final String TAG = CustomHeaderRequest.class.getSimpleName();
	
	private final IsCacheListener<String> mlistener;
	
	/**
	 * Http response status is 304 , is true
	 */
	private boolean notModified = false;

	public CustomHeaderRequest(int method, String url,
			IsCacheListener<String> listener, ErrorListener errorListener) {
		super(method, url, null, errorListener);
		this.mlistener = listener;
	}
	
	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		this.notModified = response.notModified ;

		String parsed = null;
        try {
    		parsed = new String(response.data, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
	}

	public CustomHeaderRequest(String url,
			IsCacheListener<String> listener, ErrorListener errorListener) {
		super(url, null, errorListener);
		this.mlistener = listener;
	}
	@Override
	public Map<String, String> getHeaders(Context context) throws AuthFailureError {
		Map<String, String> headers = new HashMap<String, String>();
		Map<String, String> apiVerifyHeader = HttpHeaderHelper.generateAPIVerifyHeader();
		Map<String, String> verifyUpdateHeader = generateVerifyUpdateHeader();
		Map<String, String> deviceInfoHeader = HttpHeaderHelper.generateDeviceInfoHeader(context);
		
		headers.putAll(apiVerifyHeader);
		headers.putAll(verifyUpdateHeader);
		headers.putAll(deviceInfoHeader);
		
		return headers;
	}
	
	/**
	 * 生成验证更新的Header
	 * @return 验证更新的header
	 */
	private Map<String, String> generateVerifyUpdateHeader() {
		String eTag = VolleyHelper.getETagByCache(getUrl());
		Map<String, String> header = new HashMap<String, String>();
		//匹配标记，用做更新数据
		header.put("If-None-Match",eTag==null?"":eTag );
		return header;
	}

	 /** Callback interface for delivering parsed responses. */
    public interface IsCacheListener<T> {
        /** Called when a response is received. */
    	/**
    	 * @param isCache 是否为缓存数据
    	 * @param response 数据
    	 */
		void onResponse(boolean isCache, T response);
    }
    
	@Override
	protected void deliverResponse(String response) {
		mlistener.onResponse(notModified, response);
	}
	
}
